import axios from 'axios'

// API基础URL - 根据后端服务地址配置
// 支持IP地址访问，从环境变量获取或使用默认值
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api/v1'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
})

// 请求拦截器 - 添加认证token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response?.status === 401) {
      // Token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 认证相关API
export const authAPI = {
  login: (credentials) => apiClient.post('/auth/login', credentials),
  logout: () => apiClient.post('/auth/logout'),
  refreshToken: () => apiClient.post('/auth/refresh'),
  getProfile: () => apiClient.get('/auth/profile'),
  updateProfile: (data) => apiClient.put('/auth/profile', data),
  changePassword: (data) => apiClient.put('/auth/password', data),
}

// 用户管理API (仅超级管理员)
export const userAPI = {
  getUsers: (params) => apiClient.get('/admin/users', { params }),
  createUser: (data) => apiClient.post('/admin/users', data),
  updateUser: (userId, data) => apiClient.put(`/admin/users/${userId}`, data),
  deleteUser: (userId) => apiClient.delete(`/admin/users/${userId}`),
  resetUserPassword: (userId) => apiClient.post(`/admin/users/${userId}/reset-password`),
}

// 设备管理API
export const deviceAPI = {
  getDevices: (params) => apiClient.get('/devices', { params }),
  getDevice: (deviceId) => apiClient.get(`/devices/${deviceId}`),
  createDevice: (data) => apiClient.post('/devices', data),
  updateDevice: (deviceId, data) => apiClient.put(`/devices/${deviceId}`, data),
  deleteDevice: (deviceId) => apiClient.delete(`/devices/${deviceId}`),
}

// 遥测数据API
export const telemetryAPI = {
  getLatestTelemetry: (deviceId) => apiClient.get(`/devices/${deviceId}/telemetry/latest`),
  getTelemetryHistory: (deviceId, params) => apiClient.get(`/devices/${deviceId}/telemetry/history`, { params }),
}

// 设备事件API
export const eventAPI = {
  getDeviceEvents: (deviceId, params) => apiClient.get(`/devices/${deviceId}/events`, { params }),
  getEventStats: (deviceId, params) => apiClient.get(`/devices/${deviceId}/events/stats`, { params }),
}

// 设备命令API
export const commandAPI = {
  sendCommand: (deviceId, data) => apiClient.post(`/devices/${deviceId}/command`, data),
  getCommandQueue: (deviceId) => apiClient.get(`/devices/${deviceId}/command/queue`),
  clearCommandQueue: (deviceId) => apiClient.delete(`/devices/${deviceId}/command/queue`),
  sendSubdeviceCommand: (deviceId, subdeviceId, data) => 
    apiClient.post(`/devices/${deviceId}/subdevices/${subdeviceId}/command`, data),
}

// 系统API
export const systemAPI = {
  healthCheck: () => apiClient.get('/system/health'),
  getSystemStats: () => apiClient.get('/system/stats'),
}

export default apiClient